package com.kl.daojishiii;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.admin.DevicePolicyManager;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.AlarmClock;
import android.provider.CalendarContract;
import android.provider.Settings;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.Constraints;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    SharedPreferences sharedPreferences;
    TextView txt_view_five;
    TextView txt_view_one;
    TextView txt_view_fifteen;
    TextView txt_view_two;
    TextView txt_view_twentyfive;
    TextView txt_view_three;
    TextView txt_view_four;
    TextView txt_view_fifty;
    TextView txt_view_sixty;

    List<TextView> arrTextViews = new ArrayList<TextView>();

    private long startTime;

    private long targetTime;
    TextView txt_view_left_time;
    TextView txt_view_target_time;
    CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        txt_view_target_time = findViewById(R.id.target_time);
        txt_view_target_time.setText("");

        txt_view_left_time = findViewById(R.id.left_time);
        txt_view_left_time.setText("");

        txt_view_five = findViewById(R.id.five);
        txt_view_one = findViewById(R.id.one);
        txt_view_fifteen = findViewById(R.id.fifteen);
        txt_view_two = findViewById(R.id.two);
        txt_view_twentyfive = findViewById(R.id.twentyfive);
        txt_view_three = findViewById(R.id.three);
        txt_view_four = findViewById(R.id.four);
        txt_view_fifty = findViewById(R.id.fifty);
        txt_view_sixty = findViewById(R.id.sixty);


        arrTextViews.add(txt_view_five);
        arrTextViews.add(txt_view_one);
        arrTextViews.add(txt_view_fifteen);
        arrTextViews.add(txt_view_two);
        arrTextViews.add(txt_view_twentyfive);
        arrTextViews.add(txt_view_three);
        arrTextViews.add(txt_view_four);
        arrTextViews.add(txt_view_fifty);
        arrTextViews.add(txt_view_sixty);
        for (int i = 0; i < arrTextViews.size(); i++) {
            TextView t = arrTextViews.get(i);
            ;
            t.setTextColor(Color.GRAY);
            t.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    start(t);
                }
            });
            t.setLongClickable(true);
            t.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    txt_view_target_time.setText("" + timeStamp2Date("HH:mm", System.currentTimeMillis() + getLongTime(t)));

                    new CountDownTimer(3000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {

                        }

                        @Override
                        public void onFinish() {
                            txt_view_target_time.setText("");
                        }
                    }.start();
                    return true;
                }
            });
        }
        //检查日历权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR)
                != PackageManager.PERMISSION_GRANTED) {
            // 最后的请求码是对应回调方法的请求码
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR}, 1001);
        } else {
//            Toast.makeText(this, "你已经有权限了，可以直接拨打电话", Toast.LENGTH_LONG).show();
        }
        //初次安装设定
        if (sharedPreferences.getBoolean("firstSetup", true)) {
            CalendarReminderUtils.deleteCalendarEvent(this, "专注");
            CalendarReminderUtils.deleteCalendarEvent(this, "起床");
            CalendarReminderUtils.addAlarm(this, "起床", "该起床了", true,
                    6, 30);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("firstSetup", false);
            editor.commit();
        }

        //按钮事件
        Button btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CalendarReminderUtils.deleteCalendarEvent(MainActivity.this, "起床");
                CalendarReminderUtils.addAlarm(MainActivity.this, "起床", "该起床了",
                        false, sharedPreferences.getInt("hour", 6),
                        sharedPreferences.getInt("minute", 30));
                long res = CalendarReminderUtils.findNext(MainActivity.this, "起床");
                TextView clockTextView = findViewById(R.id.clock);
                clockTextView.setText(MainActivity.timeStamp2Date("MM-dd HH:mm", res));
            }
        });

        //调整闹钟按钮
        Button btnEdit = findViewById(R.id.btn_edit);


        btnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //弹窗
                TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, 2,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putInt("hour", hourOfDay);
                                editor.putInt("minute", minute);
                                editor.commit();

                                CalendarReminderUtils.deleteCalendarEvent(MainActivity.this, "起床");
                                CalendarReminderUtils.addAlarm(MainActivity.this, "起床", "该起床了",
                                        true, hourOfDay, minute);
                                long res = CalendarReminderUtils.findNext(MainActivity.this, "起床");
                                TextView clockTextView = findViewById(R.id.clock);
                                clockTextView.setText(MainActivity.timeStamp2Date("MM-dd HH:mm", res));
                            }
                        }, 0, 0, true);

                timePickerDialog.updateTime(sharedPreferences.getInt("hour", 6),
                        sharedPreferences.getInt("minute", 30));
                timePickerDialog.show();

            }
        });
    }

    private static String timeStamp2Date(String format, long time) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(time));
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("skl", "onResume");
        //清理过期的专注日历
        if (System.currentTimeMillis() > targetTime) {
            clear();
        }
        //更新系统显示时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        Date date = new Date(System.currentTimeMillis());
        TextView textView = findViewById(R.id.time);
        textView.setText(simpleDateFormat.format(date));
        //更新下个闹钟显示
        long res = CalendarReminderUtils.findNext(MainActivity.this, "起床");
        if (System.currentTimeMillis() > res) {
            CalendarReminderUtils.deleteCalendarEvent(MainActivity.this, "起床");
            CalendarReminderUtils.addAlarm(MainActivity.this, "起床", "该起床了", false,
                    sharedPreferences.getInt("hour", 6),
                    sharedPreferences.getInt("minute", 30));
            res = CalendarReminderUtils.findNext(MainActivity.this, "起床");
        }
        TextView clockTextView = findViewById(R.id.clock);
        clockTextView.setText(MainActivity.timeStamp2Date("MM-dd HH:mm", res));

    }

    //清空所有专注日历
    private void clear() {
        for (int i = 0; i < arrTextViews.size(); i++) {
            TextView t = arrTextViews.get(i);
            t.setClickable(true);
            t.setTextColor(Color.GRAY);
        }
        TextView t = findViewById(R.id.time);
        t.setTextColor(Color.BLACK);
        CalendarReminderUtils.deleteCalendarEvent(this, "专注");
    }

    @SuppressLint("ResourceAsColor")
    private void start(TextView textView) {

        int colorState = textView.getCurrentTextColor();
        TextView timeTextView = (TextView) findViewById(R.id.time);
        if (colorState != Color.GREEN) {
            //开始专注
            textView.setTextColor(Color.GREEN);

            timeTextView.setTextColor(Color.GREEN);
            //静止点击
            for (int i = 0; i < arrTextViews.size(); i++) {
                TextView t = arrTextViews.get(i);
                t.setClickable(false);
            }
            textView.setClickable(true);
            //获取时长
            long time = getLongTime(textView);
            startTime = System.currentTimeMillis();
            targetTime = startTime + time;
            CalendarReminderUtils.addCalendarEvent
                    (this, "专注", "定时专注",
                            targetTime, 2);
            txt_view_target_time.setText("" + timeStamp2Date("HH:mm", targetTime));
            countDownTimer = new CountDownTimer(time, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    txt_view_left_time.setText("剩余" + millisUntilFinished / 1000 / 60 % 60 + ":" + millisUntilFinished / 1000 % 60);
                }

                @Override
                public void onFinish() {
                    txt_view_left_time.setText("");
                    txt_view_target_time.setText("");
                }
            }.start();
        } else {
            countDownTimer.cancel();
            txt_view_target_time.setText("");
            txt_view_left_time.setText("");
            timeTextView.setTextColor(Color.BLACK);
            textView.setTextColor(Color.GRAY);
            //结束专注
            for (int i = 0; i < arrTextViews.size(); i++) {
                TextView t = arrTextViews.get(i);
                t.setClickable(true);
            }
            CalendarReminderUtils.deleteCalendarEvent(this, "专注");
        }
    }


    private void showText(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();

    }

    private long getLongTime(TextView textView) {
        long time = 0;
        switch (textView.getId()) {
            case R.id.five:
                time = 1000 * 60 * 5;
                break;
            case R.id.one:
                time = 1000 * 60 * 10;
                break;
            case R.id.fifteen:
                time = 1000 * 60 * 15;
                break;
            case R.id.two:
                time = 1000 * 60 * 20;
                break;
            case R.id.twentyfive:
                time = 1000 * 60 * 25;
                break;
            case R.id.three:
                time = 1000 * 60 * 30;
                break;
            case R.id.four:
                time = 1000 * 60 * 40;
                break;
            case R.id.fifty:
                time = 1000 * 60 * 50;
                break;
            case R.id.sixty:
                time = 1000 * 60 * 60;
                break;
        }
        return time;
    }
}